import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建 axios 实例
const service = axios.create({
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        const config = response.config

        // 如果设置了 skipCodeCheck，则直接返回完整响应
        if (config.skipCodeCheck) {
            return response
        }

        // 如果后端返回自定义 code 不为 200，视为业务错误
        if (res.code !== 200) {
            ElMessage.error(res.message || 'Error')
            return Promise.reject(new Error(res.message || 'Error'))
        }

        return res
    },
    error => {
        if (error.response) {
            const status = error.response.status
            if (status === 401) {
                ElMessage.error('登录已失效，请重新登录')
                localStorage.removeItem('token')
                router.push('/login').then(() => {})
                return Promise.resolve({ code: 401, message: 'Unauthorized', data: null })
            } else if (status === 403) {
                ElMessage.error('IP被拦截')
                localStorage.removeItem('token')
                router.push('/login').then(() => {})
                return Promise.resolve({ code: 403, message: 'Forbidden', data: null })
            } else if (status === 429) {
                ElMessage.warning('请求太频繁，请稍后再试')
            } else {
                // ElMessage.error(error.response.data.message || '请求失败')
            }
        } else {
            ElMessage.error('网络错误或服务不可用')
        }
        return Promise.reject(error)
    }
)

export default service
